<?php

define('APP_PATH', dirname(dirname(__FILE__)));
require_once(APP_PATH . '/app.php');

$authkey = $_G['gp_authkey'] ? htmlspecialchars($_G['gp_authkey']) : '';
$secret = $_G['gp_secret'] ? htmlspecialchars($_G['gp_secret']) : '';
$agent = $_G['gp_agent'] ? htmlspecialchars($_G['gp_agent']) : '';
$agent_info = $_G['gp_agent_info'] ? htmlspecialchars($_G['gp_agent_info']) : '';

if( $agent_info ){
	if( $_G['gp_agent_info_encode'] == 'base64' ){
		$agent_info = base64_decode($agent_info);
	}
	if( $agent_info ){
		$agent_data = parse_agent_info($agent_info);
	}
}

$app = fetch('team', array(
	'key' => $authkey,
	'secret' => $secret	
));

if( !$app ){
	jsonp(array(
		'auth' => -1,
		'ecode' => -1,
		'data' => '验证失败',
	));
}

$log = array(
	'teamid' => $app['id'],
	'agent' => $agent,
	'agent_info' => $agent_info,
	'ecode' => 0,
	'description' => '通过',
	'create_time' => time()
);

if( !$agent ){
	$noagent = array(
		'auth' => -1,
		'ecode' => 2003,
		'data' => '不支持该设备',
	);
	$log['description'] = $noagent['data'];
	$log['ecode'] = $noagent['ecode'];
	DB::Insert('team_auth', $log);
	jsonp($noagent);
}

if( $app['status'] ){
	$noallow = array(
		'auth' => -1,
		'ecode' => 1045,
		'data' => '程序被限制使用',
		'agent_data' => $agent_data,
		'only_alert' => 0
	);
	$log['description'] = $noallow['data'];
	$log['ecode'] = $noallow['ecode'];
	DB::Insert('team_auth', $log);
	jsonp($noallow);
}

$last_use = limitquery('team_auth', array('teamid' => $app['id']), array('order' => 'ORDER BY `create_time` ASC'), 0, 1);

$day = $app['expire'] ? $app['expire'] : 30;

$data = array(
	'auth' => 1,
	'status' => 0,
	'time' => time(),
	'microtime' => microtime(true),
	'code' => authcode($authkey, 'ENCODE', $secret, $day * 86400),
	'agent' => $agent,
	'agent_info' => $agent_info ? $agent_info : '',
	'confirm' => 0,
	'only_alert' => 0,
);
$log['code'] = $data['code'];
if( $authkey == 'shanghaijiaoxiangyue_ipad' ){
	$data['confirm'] = 1;
}
DB::Insert('team_auth', $log);

update('team', $app['id'], array(
	'last_auth_time' => time()
));
jsonp($data);

function parse_agent_info($agent_info = ''){
	$agent_info = str_replace(array(' : ', ', '), array(':', ','), $agent_info);
	$infos = explode(',', $agent_info);
	$datas = array();
	foreach( $infos as $k => $v ){
		$info = explode(':', $v);
		$datas[$info[0]] = $info[1];
	}
	return $datas;
}
?>